package com.om.common;

import com.om.base.AbstractBean;
import com.om.base.BeanFactory;
import com.om.base.ChildRelation;
import com.om.base.LuceneIndex;
import com.om.base.LuceneUtils;
import com.om.base.SqlFilter;
import com.om.base.Utils;
import com.om.pages.PageInfo;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.util.Version;

/**
 * 继承了了AbstractBean类， 实现了initColumns（）方法,实现了AbstractBean对象内部字段信息的初始化
 * 实现了save方法,自动更具实际情况去调用基类的insertItem()和updateItem()
 * 
 * @author Administrator
 *
 */
public class BaseBean<T> extends AbstractBean {

	/**
	 * 自动根据实际情况调用基类的inserItem和updateItem
	 * 
	 * @return 成功为true,失败为false
	 * @throws Exception
	 */
	public boolean save() throws Exception {

		boolean success = false;
		String errorEmpty = "101";
		String errorUnique = "102";

		if (this.connection == null) {
			this.connection = Utils.GetOpenedWriteConnection();
		}
		String field = this.emptyCheck();
		if (!"".equals(field)) {
			HashMap<String, Object> data = new HashMap<String, Object>();
			data.put("field", field);
			data.put("value", this.get(field));
			if (ConfigReader.GetProptery("error.empty") != "") {
				errorEmpty = ConfigReader.GetProptery("error.empty");
			}

			throw new BaseCustomerExecption(errorEmpty, data);
		}

		if (!this.validate) {
			field = this.uniqueCheck();
			if (!field.equals("")) {
				HashMap<String, Object> data = new HashMap<String, Object>();
				data.put("field", field);
				data.put("value", this.get(field));
				if (ConfigReader.GetProptery("error.unique") != "") {
					errorUnique = ConfigReader.GetProptery("error.unique");
				}
				throw new BaseCustomerExecption(errorUnique, data);
			}
		}

		if (this.Field.length == 0) {
			initColumns();
		}
		if (isNew()) {
			success = insertItem().booleanValue();
		} else {
			success = updateItem().booleanValue();
		}
		childProceed();
		return success;
		//this.childProceed(this);
		/*Object[] keys = this.childMap.keySet().toArray();
		if (keys != null) {
			for (int j = 0; j < keys.length; j++) {
				ChildRelation rel = (ChildRelation) this.childMap.get(keys[j]);
				Object key = Class.forName(keys[j].toString()).getSimpleName();
				if (!this.childrenData.containsKey(key))
					continue;

				List<T> children = (List<T>) this.childrenData.get(key);

				for (int i = 0; i < children.size(); i++) {
					BaseBean bean = (BaseBean) children.get(i);
					bean.set(rel.foreignColumn, this.get(rel.localColumn));
					bean.parentNode = this;
					if (bean.containsKey(AbstractBean.DATA_ROW_STATE)) {
						String state = bean
								.getStringValue(AbstractBean.DATA_ROW_STATE);

						if (AbstractBean.NO_CHANGE.equals(state)) {
							continue;
						}

						if (AbstractBean.DELETED.equals(state)) {
							bean.deleteItem();
						} else {
							
							//bean.save();
						}

					}

				}

			}

		}
		this.set(AbstractBean.KEY_VALUE, this.getKeyValue());

		// 创建/更新Lucene索引
		if (this.LuceneIndexClass != null) {
			Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);
			String className = ConfigReader
					.GetProptery("lucene.analyzer.class");
			if (!className.equals("")) {
				analyzer = (Analyzer) Class.forName(className).newInstance();
			}
			Object key = this.getKeyValue();
			if (key == null || "".equals(key)) {
				key = this.get(this.PrimaryKey);
			}
			if (key != null && !"".equals(key)) {
				LuceneIndex index = (LuceneIndex) BeanFactory.LoadBean(
						this.LuceneIndexClass, key);
				LuceneUtils.SaveIndex(index, analyzer);
			}

		}
*/
		
	}
	
	public  void childProceed() throws Exception{
		Object[] keys = this.childMap.keySet().toArray();
		if (keys != null) {
			for (int j = 0; j < keys.length; j++) {
				ChildRelation rel = (ChildRelation) this.childMap.get(keys[j]);
				Object key = Class.forName(keys[j].toString()).getSimpleName();
				if (!this.childrenData.containsKey(key))
					continue;

				List<T> children = (List<T>) this.childrenData.get(key);

				for (int i = 0; i < children.size(); i++) {
					BaseBean bean = (BaseBean) children.get(i);
					bean.set(rel.foreignColumn, this.get(rel.localColumn));
					bean.parentNode = this;
					if (bean.containsKey(AbstractBean.DATA_ROW_STATE)) {
						String state = bean.getStringValue(AbstractBean.DATA_ROW_STATE);

						if (AbstractBean.NO_CHANGE.equals(state)) {
							continue;
						}

						if (AbstractBean.DELETED.equals(state)) {
							bean.deleteItem();
						} else {
							Method method = bean.getClass().getMethod(rel.chainMethod,null);
							method.setAccessible(true);
							method.invoke(bean, null);
						}

					}

				}

			}

		}
		this.set(AbstractBean.KEY_VALUE, this.getKeyValue());

		// 创建/更新Lucene索引
		if (this.LuceneIndexClass != null) {
			Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);
			String className = ConfigReader.GetProptery("lucene.analyzer.class");
			if (!className.equals("")) {
				analyzer = (Analyzer) Class.forName(className).newInstance();
			}
			Object key = this.getKeyValue();
			if (key == null || "".equals(key)) {
				key = this.get(this.PrimaryKey);
			}
			if (key != null && !"".equals(key)) {
				LuceneIndex index = (LuceneIndex) BeanFactory.LoadBean(this.LuceneIndexClass, key);
				LuceneUtils.SaveIndex(index, analyzer);
			}

		}
		
	}

	@Override
	public List getBeanList(SqlFilter filter, PageInfo page) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List getBeanList(SqlFilter filter, int startIndex, int endIndex) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List getBeanList(SqlFilter filter, String orderBy) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List getBeanList(SqlFilter filter, String orderBy,
			String selectColumns) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
